package longrise.phone.com.bjjt_henan.main;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.longrise.LEAP.Base.Objects.EntityBean;
import com.longrise.bjjt.BaseApplication;
import com.longrise.bjjt.util.UiUtil;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.umeng.socialize.utils.SocializeUtils;

import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;

import longrise.phone.com.bjjt_henan.R;
import longrise.phone.com.bjjt_henan.Utils.ApiImpI;
import longrise.phone.com.bjjt_henan.Utils.CommontUtils;
import longrise.phone.com.bjjt_henan.Utils.PermissionHelper;
import longrise.phone.com.bjjt_henan.Utils.WebViewHelper;
import longrise.phone.com.bjjt_henan.tinker.TinkerApplicationLike;
import longrise.phone.com.bjjt_henan.tinker.util.TinkerManager;

/**
 * 车主头条
 */
public class CarNewsActivity extends Activity implements View.OnClickListener {

    private static final int LOAD_URL = 0;

    private WebViewHelper webViewHelper;

    private BaseApplication application;

    private Dialog dialog;

    private MyHandler mHanler;

    private Stack mStack;//存放访问历史的堆栈

    private LinearLayout collectLayout;

    private ImageView collectIV;

    private LinearLayout shareLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //无title
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);

        LinearLayout bodyLayout = new LinearLayout(this);
        bodyLayout.setOrientation(LinearLayout.VERTICAL);
        //标题栏
        View titleView = View.inflate(this, R.layout.activity_carnews, null);
        LinearLayout.LayoutParams titleParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, UiUtil.dip2Px(50));
        bodyLayout.addView(titleView, titleParams);
        titleParams = null;
        //网页
        if (null == webViewHelper) {
            webViewHelper = new WebViewHelper(this);
        }
        View webView = webViewHelper.getView();
        LinearLayout.LayoutParams webParams = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        bodyLayout.addView(webView, webParams);
        webParams = null;

        setContentView(bodyLayout);

        initViews();
        initValues();
    }

    private void initViews() {
        // 返回操作
        findViewById(R.id.hn_btn_back).setOnClickListener(this);
        collectLayout = (LinearLayout) findViewById(R.id.carnews_layout_collect);
        collectIV = (ImageView) findViewById(R.id.carnews_iv_collect);
        collectLayout.setOnClickListener(this);
        shareLayout = (LinearLayout) findViewById(R.id.carnews_layout_share);
        shareLayout.setOnClickListener(this);
    }

    //获取tinker的application代理类
    public TinkerApplicationLike getAppLike() {
        return (TinkerApplicationLike) TinkerManager.getTinkerApplicationLike();
    }

    //获取数据实体类
    public BaseApplication getAppData() {
        return (getAppLike() == null) ? null : getAppLike().getDataApp();
    }

    private void initValues() {
        application = this.getAppData();
        mHanler = new MyHandler(this);
        mStack = new Stack();

        //Android执行js脚本
        webViewHelper.addJSInterface(new JSObject(), "jsobj");

        HashMap bean = (HashMap) getIntent().getSerializableExtra("databean");
        if (bean != null) {
            String url = (String) bean.get("url");
            webViewHelper.loadUrl(url);

            mStack.push(bean);
            checkCollect(url);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.hn_btn_back://返回
                onBackPressed();
                break;
            case R.id.carnews_layout_collect://收藏
                String curUrl = webViewHelper.getCurrentUrl();
                collectNews(curUrl);
                break;
            case R.id.carnews_layout_share://分享
                shareNews();
                break;
            default:
                break;
        }
    }

    //收藏新闻消息
    private void collectNews(String url) {
        Uri uri = Uri.parse(url);
        String id = uri.getQueryParameter("id");
        String userflag = application.getKckpName();
        String token = application.getToken();
        if (dialog == null) {
            dialog = UiUtil.showProcessDialog(this, "加载中...");
        } else {
            dialog.show();
        }
        ApiImpI.getInstance(this.getApplicationContext()).collectNews(userflag, token, id, new ApiImpI.RequestCallBack() {
            @Override
            public void onError(String error) {
                if (dialog == null) {
                    return;
                }
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                if (!TextUtils.isEmpty(error)) {
                    UiUtil.showToast(CarNewsActivity.this, error);
                }
            }

            @Override
            public void onSuccess(Object result) {
                if (dialog == null) {
                    return;
                }
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                EntityBean bean = (EntityBean) result;
                String restate = bean.getString("restate");
                HashMap map = (HashMap) mStack.peek();
                if (TextUtils.equals(restate, "1")) {//收藏
                    map.put("isCollect", "1");
                    showCollectImg("1");
                } else if (TextUtils.equals(restate, "2")) {//取消收藏
                    map.put("isCollect", "0");
                    showCollectImg("0");
                }
                String redes = bean.getString("redes");
                UiUtil.showToast(CarNewsActivity.this, redes);
            }
        });
    }

    //检测是否收藏
    private void checkCollect(String url) {
        Uri uri = Uri.parse(url);
        String id = uri.getQueryParameter("id");
        if (TextUtils.isEmpty(id)) {
            HashMap map = (HashMap) mStack.peek();
            map.put("isCollect", "-1");
            collectLayout.setVisibility(View.INVISIBLE);
            shareLayout.setVisibility(View.INVISIBLE);
            return;
        }
        String userflag = application.getKckpName();
        String token = application.getToken();
        if (dialog == null) {
            dialog = UiUtil.showProcessDialog(this, "加载中...");
        } else {
            dialog.show();
        }
        ApiImpI.getInstance(this.getApplicationContext()).checkCollect(userflag, token, id, new ApiImpI.RequestCallBack() {
            @Override
            public void onError(String error) {
                if (dialog == null) {
                    return;
                }
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                if (!TextUtils.isEmpty(error)) {
                    UiUtil.showToast(CarNewsActivity.this, error);
                }
            }

            @Override
            public void onSuccess(Object result) {
                if (dialog == null) {
                    return;
                }
                if (dialog.isShowing()) {
                    dialog.dismiss();
                }
                EntityBean bean = (EntityBean) result;
                String restate = bean.getString("restate");
                if (TextUtils.equals(restate, "1")) {
                    if (null == mStack) {
                        return;
                    }
                    String iscol = bean.getBean("data").getString("iscol");
                    HashMap map = (HashMap) mStack.peek();
                    map.put("isCollect", iscol);
                    showCollectImg(iscol);
                }
            }
        });
    }

    //显示收藏的图标
    private void showCollectImg(String iscollect) {
        collectLayout.setVisibility(View.VISIBLE);
        shareLayout.setVisibility(View.VISIBLE);
        if (TextUtils.equals(iscollect, "1")) {//已收藏
            collectIV.setBackgroundResource(R.mipmap.star_on);
        } else if (TextUtils.equals(iscollect, "0")) {//未收藏
            collectIV.setBackgroundResource(R.mipmap.star);
        } else if (TextUtils.equals(iscollect, "-1")) {
            collectLayout.setVisibility(View.INVISIBLE);
            shareLayout.setVisibility(View.INVISIBLE);
        }
    }

    //分享新闻
    private void shareNews() {
        if (!PermissionHelper.checkPermissions(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
            return;
        }
        if (mStack.empty()) {
            UiUtil.showToast(this, "参数有误，请退出后重新分享！");
            return;
        }
        HashMap map = (HashMap) mStack.peek();
        ShareAction action = new ShareAction(this);
        action.setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ, SHARE_MEDIA.QZONE);

        UMImage thumb = null;
        String img = (String) map.get("imgtitle");
        if (TextUtils.isEmpty(img)) {
            thumb = new UMImage(this, R.mipmap.logo09);
        } else {
            img = CommontUtils.encodeUrlString(img);
            thumb = new UMImage(this, img);
        }
        UMWeb web = new UMWeb((String) map.get("url"));
        web.setTitle((String) map.get("title"));//标题
        web.setDescription("  ");//描述
        web.setThumb(thumb);  //缩略图

        action.withMedia(web);
        action.setCallback(umShareListener);
        action.open();
    }

    private ProgressDialog umDialog;

    private UMShareListener umShareListener = new UMShareListener() {

        @Override
        public void onStart(SHARE_MEDIA platform) {
            if (umDialog == null) {
                umDialog = new ProgressDialog(CarNewsActivity.this);
            }
            SocializeUtils.safeShowDialog(umDialog);
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            if (platform.name().equals("WEIXIN_FAVORITE")) {
                UiUtil.showToast(CarNewsActivity.this, "收藏成功");
            } else {
                UiUtil.showToast(CarNewsActivity.this, "分享成功");
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            SocializeUtils.safeCloseDialog(umDialog);
            String throwMsg = null;
            if (t != null) {
                throwMsg = t.getMessage();
            }
            if (TextUtils.isEmpty(throwMsg)) {
                throwMsg = "分享失败";
            }
            UiUtil.showToast(CarNewsActivity.this, throwMsg);
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
//            UiUtil.showToast(CarNewsActivity.this, " 分享取消");
        }
    };

    @Override
    public void onBackPressed() {
        if (null != webViewHelper && webViewHelper.goBackView()) {
            if (!mStack.empty()) {
                mStack.pop();//出栈
                if (!mStack.empty()) {
                    HashMap map = (HashMap) mStack.peek();
                    String iscol = (String) map.get("isCollect");
                    showCollectImg(iscol);
                }
            }
            return;
        }
        super.onBackPressed();
    }

    @Override
    protected void onResume() {
        super.onResume();
        SocializeUtils.safeCloseDialog(umDialog);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onDestroy() {
        if (null != webViewHelper) {
            webViewHelper.closeView();
        }
        webViewHelper = null;
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
        if (null != mHanler) {
            mHanler.removeMessages(LOAD_URL);
            mHanler = null;
        }
        if (null != mStack) {
            mStack.clear();
            mStack = null;
        }
        UMShareAPI.get(this).release();
        super.onDestroy();
    }

    //将浏览历史压入栈中
    private void pushData(String params) {
        try {
            if (params == null) {
                return;
            }
            JSONObject obj = new JSONObject(params);
            Map map = new HashMap();
            map.put("imgtitle", obj.getString("imgtitle"));
            map.put("title", obj.getString("title"));
            map.put("url", obj.getString("url"));
            mStack.push(map);
            checkCollect(obj.getString("url"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static class MyHandler extends Handler {

        private WeakReference<CarNewsActivity> reference;

        public MyHandler(CarNewsActivity activity) {
            reference = new WeakReference<CarNewsActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            final CarNewsActivity activity = reference.get();
            if (null == activity) {
                return;
            }
            switch (msg.what) {
                case LOAD_URL:
                    activity.pushData((String) msg.obj);
                    break;
                default:
                    break;
            }
        }
    }

    //js交互类
    private class JSObject {

        //加载其他页面
        @JavascriptInterface
        public void loadUrl(String params) {
            Log.i("loadUrl", params);
            Message msg = Message.obtain();
            msg.obj = params;
            msg.what = LOAD_URL;
            mHanler.sendMessage(msg);
        }
    }
}
